import React, { useState, useEffect } from "react";
import "./assets/css/ArticleList.css";
import { Modal, message, Button, Space, Table } from "antd";
import axios from "axios";
import servicePath from "./config/apiUrl";
const { confirm } = Modal;

const ArticleList = (props) => {
  const [list, setList] = useState([]);

  const columns = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "类别",
      dataIndex: "type_name",
      key: "type_name",
    },
    {
      title: "发布时间",
      dataIndex: "created_at",
      key: "created_at",
    },
    {
      title: "浏览量",
      dataIndex: "view_count",
      key: "view_count",
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (value, row) => (
        <Space>
          <Button type="primary" onClick={updateArticle.bind(this, row.id)}>
            修改
          </Button>
          <Button
            onClick={() => {
              delArticle(row.id);
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  //得到文章列表
  const getList = () => {
    axios({
      method: "get",
      url: servicePath.getArticleList,
      withCredentials: true,
      header: { "Access-Control-Allow-Origin": "*" },
    }).then((res) => {
      setList(res.data.list.map(item => {
        item.key = item.id
        return item;
      }));
    });
  };

  //删除文章的方法
  const delArticle = (id) => {
    confirm({
      title: "确定要删除这篇博客文章吗?",
      content: "如果你点击OK按钮，文章将会永远被删除，无法恢复。",
      onOk() {
        axios(servicePath.delArticle + id, { withCredentials: true }).then(
          (res) => {
            message.success("文章删除成功");
            getList();
          }
        );
      },
      onCancel() {
        message.success("没有任何改变");
      },
    });
  };

  //修改文章
  const updateArticle = (id) => {
    props.history.push("/index/add/" + id);
  };

  useEffect(() => {
    getList();
  }, []);

  return (
    <Table dataSource={list} columns={columns} />
  );
}

export default ArticleList;
